package ch03;

import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.List;

/**
 * @author yang
 * @date 2024-04-03
 */
public class Student {
    private String name;

    @Information()
    private String sex;

    @Information()
    private String[] hobby;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) throws Exception{
        checkSex(sex);
        this.sex = sex;
    }

    public String[] getHobby() throws Exception{
        this.hobby = getHobbyAll();
        return hobby;
    }

    public void setHobby(String[] hobby) {
        this.hobby = hobby;
    }

    public Student() {
    }

    public Student(String name, String sex, String[] hobby) {
        this.name = name;
        this.sex = sex;
        this.hobby = hobby;
    }

    /**
     * 检查输入性别
     */
    public void checkSex(String sex) throws Exception {
        // 获取 Student 字节码对象
        Class<Student> studentClass = Student.class;
        // 获取方法对象
        Field declaredField = studentClass.getDeclaredField("sex");
        // 判断方法是否存在注解
        if (declaredField.isAnnotationPresent(Information.class)){
            // 获取注解的 sex 对象并转换成 List 集合对象
            String[] sexAll = declaredField.getAnnotation(Information.class).sex();
            List<String> sexList = Arrays.asList(sexAll);
            //判断输入的参数是否包含在 List 集合对象中
            if (!sexList.contains(sex)){
                throw new RuntimeException("性别输入错误");
            }
        }
    }

    /**
     * 获取学生的爱好
     *
     * @return
     */
    public String[] getHobbyAll() throws Exception{
        // 获取 Student 的字节码对象
        Class<Student> studentClass = Student.class;
        // 获取 Student 类的 hobby 属性对象
        Field declaredField = studentClass.getDeclaredField("hobby");

        String[] hobbyAll = {};
        // 判断是否存在注解
        if (declaredField.isAnnotationPresent(Information.class)) {
            // 获取注解 Information 里 hobby 的值
            hobbyAll = declaredField.getAnnotation(Information.class).hobby();
        }
        return hobbyAll;
    }
}
